﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class ContentController : Base
{
    private readonly ApplicationContext _applicationContext;
    private readonly ContentService _contentService;
    private readonly ContentCateService _contentCateService;
    private readonly AttmentService _attment;
    private readonly UserService _adminUserService;
    public ContentController(ApplicationContext applicationContext, ContentService contentService, ContentCateService contentCateService,
      AttmentService attmentService, UserService adminUserService)
    {
        _applicationContext = applicationContext;
        _contentService = contentService;
        _contentCateService = contentCateService;
        _attment = attmentService;
        _adminUserService = adminUserService;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] ContentQuery query, int cid = 0)
    {
        ILoginUserInfo user = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        query.Uid = user.UserId;
        query.Uids = await _adminUserService.UserPostAsUids(user);
        query.Cids = cid == 0 ? null : new int[] { cid };
        IEnumerable<CategoryViewModel> catelist = await _contentCateService.GetContentCateListAsync(user);
        PagedInfo<ViewContentAndCate> pagedList = await _contentService.GetListAynsc(query);
        return Success(new { count = pagedList.TotalNum, data = pagedList.Result, catelist });
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        ILoginUserInfo user = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        IEnumerable<CategoryViewModel> cateList = await _contentCateService.GetContentCateListAsync(user);
        if (id < 1)
            return Success(new { cateList });
        EditContentAndContent data = await _contentService.GetEditAsync(id);
        List<Attment> attments = null;
        if (!string.IsNullOrEmpty(data.Attments))
        {
            List<int> attIds = data.Attments.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
            attments = await _attment.GetListAsync(attIds);
        }
        return Success(new { data, attments, cateList });
    }

    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEdit)]
    [Log(Name = "新增内容")]
    public async Task<IActionResult> CreatePostAsync([FromBody] EditContentAndContent contentPost)
    {
        ILoginUserInfo adminUser = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        Content content = contentPost.Adapt<Content>();
        ContentContent contentData = contentPost.Adapt<ContentContent>();
        content.Uid = adminUser.UserId;
        int contentInsertId = await _contentService.InsertContentAndDataAsync(content, contentData);
        if (contentInsertId > 0)
            return Success($"新增内容 Id: {contentInsertId} ; 标题：{contentPost.Title}");
        else
            return Fail("新增失败！");
    }
    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEdit)]
    [Log(Name = "修改内容")]
    public async Task<IActionResult> EditPostAsync([FromBody] EditContentAndContent contentPost)
    {
        Content content = contentPost.Adapt<Content>();
        ContentContent contentData = contentPost.Adapt<ContentContent>();
        int x = await _contentService.UpdateContentAndDataAsync(content, contentData);
        if (x > 0)
            return Success($"修改内容 ID：{contentPost.Id} ; 标题：{contentPost.Title}");
        else
            return Fail("修改失败！");
    }
    [HttpPut]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Status)]
    [Log(Name = "设置内容属性")]
    public async Task<IActionResult> SwitchValue([FromBody] ContentFormChange formChange)
    {
        if (await _contentService.UpdateContentAttAsync(formChange) < 1)
            return Fail("设置失败！");
        string title = formChange.Val == true ? "设置" : "取消设置";
        return Success($"{title} {formChange.Title} ; ID：{formChange.Id}");
    }
    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Delete)]
    [Log(Name = "删除文章")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _contentService.DelContentAndContentAsync(id) > 0)
            return Success($"删除内容 ;ID：{id}");
        else
            return Fail("删除失败！");
    }
}
